package com.lgr.store.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lgr.store.service.OrderService;
import com.lgr.store.utils.AppointStateEnum;
import com.lgr.store.utils.ContextUtils;
import com.lgr.store.utils.LogJournal;
import com.lgr.store.utils.PageObject;
import com.lgr.store.vo.DepVo;
import com.lgr.store.vo.EmpVo;
import com.lgr.store.vo.MaterialVo;
import com.lgr.store.vo.OrderDetailVo;
import com.lgr.store.vo.OrdersVo;
import com.lgr.store.vo.StorageVo;
import com.lgr.store.vo.SupplierVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/admin/orderBack")
public class OrderBackController {
    @Resource
    OrderService ordService;
    @Resource
    HttpSession session;
  //返回上传结果
    private String errinfo;
    
    @RequestMapping(value="/list")
    public String list(HttpServletRequest request,HttpServletResponse response, OrdersVo ord, PageObject pager, ModelMap map){
        int cnt = 0;
        if(ord.getEmpName()==null ){
        	if(session.getAttribute("order")==null){
        		ord.setInvalid(-1);
        		ord.setAduitStatus(-1);
        	}else{
        		ord = (OrdersVo)session.getAttribute("order");
        	}
        }else{
        	session.setAttribute("order",ord);
        }
        String sdate1=ord.getOrderDate();
        String sdate2=ord.getOrderDate2();
        ord.setOrderType(2);//退货单
        if(ord.getOrderDate()!=null && ord.getOrderDate()!="" && ord.getOrderDate2()!=null && ord.getOrderDate2()!="" && ord.getOrderDate().length()<=10){
        	ord.setOrderDate(ord.getOrderDate() +" 00:00:00");
        	ord.setOrderDate2(ord.getOrderDate2() +" 23:59:59");
        }
        
        try{
            cnt = ordService.count(ord);
            System.out.println("....................."+cnt);
        }catch(Exception e){
            e.printStackTrace();
        }
        pager.setTotalRows(cnt);
        List<OrdersVo> ordList = ordService.list(ord,pager);
        ord.setOrderDate(sdate1);
        ord.setOrderDate2(sdate2);
        map.addAttribute("ord",ord);
        pager.setDatas(ordList);
        map.addAttribute("pager",pager);

		//所有供应商
		List<SupplierVo> supplierList = ordService.findAllSupplier();
		map.addAttribute("supplierList",supplierList);
        request.getSession().setAttribute("ord", ord);
        return "orderBackList";	

    }
    @RequestMapping(value = "/init")
    public String init(OrdersVo ord,ModelMap map){
		//所有供应商
		List<SupplierVo> supplierList = ordService.findAllSupplier();
		map.addAttribute("supplierList",supplierList);
        ord.setInvalid(1);
        ord.setAduitStatus(0);
        map.addAttribute("ord",ord);
    	return "orderBackAdd";
    }
    //获取订单号
    public String getOrderId(){
    	Map<String, String> params = new HashMap<String, String>();
        String orderNo = null;
        params.put("itemType", ContextUtils.ITEMTYPE[1]);
        params.put("orderId", orderNo);
        ordService.getOrderId(params);
        return  params.get("orderId");
       
    }
    //新增或修改
    @ResponseBody
    @RequestMapping(value = "/save")
    public Map add(HttpServletRequest request,HttpServletResponse response, OrdersVo ord){
    	//新增
    	errinfo="";
    	boolean bAdd = false;
    	Map map = new HashMap();
    	String orderNo=ord.getOrderNo();
    	EmpVo empVo = (EmpVo) session.getAttribute(AppointStateEnum.EMPS.getStateInfo());
    	if(ord.getOrderNo()==null || ord.getOrderNo().equals("")){
    		orderNo = getOrderId();
    		ord.setOrderNo(orderNo);
    		ord.setOprDate(ContextUtils.dateToStrLong(new Date()));
    		ord.setEmpName(empVo.getEmpName());
    		bAdd=true;
    	}
		List<OrderDetailVo> detailList = new ArrayList<OrderDetailVo>();
		String detailData = ord.getDetailData();
		String [] rows = detailData.split(";");
		for (int i=0;i<rows.length;i++) {
			String [] row = rows[i].split(",");
			OrderDetailVo detail = new OrderDetailVo();
			if(row[0]==null || row[0].equals("")){
				detail.setOrderDetailId(0);
			}else{
				detail.setOrderDetailId(Integer.parseInt(row[0]));
			}
			detail.setOrderNo(orderNo);
			detail.setOrderId(row[6]);
			detail.setBatchNo(row[7]);
			detail.setOrderFlag(row[9]);
			detail.setStorageId(Integer.parseInt(row[10]));
			detail.setStorageName(row[11]);
			if(detail.getOrderFlag().equals("冲红")){
				detail.setOrderCnt(Math.abs(Float.parseFloat(row[8])));
			}else{
				detail.setOrderCnt(-Math.abs(Float.parseFloat(row[8])));
			}
			MaterialVo material = ordService.findMaterialByCode2(Integer.parseInt(row[12]));
			if(material==null){
				errinfo += "第"+(i+1)+"行物料编码不存在;";
				continue;
			}else{
				detail.setMaterialId(material.getMaterialId());
				detail.setMaterialCode(material.getMaterialCode());
				detail.setMaterialName(material.getMaterialName());
				detail.setStyle(material.getStyle());
				detail.setMaterialUnit(material.getMaterialUnit());
			}
			detailList.add(detail);
		}
		if(!errinfo.equals("")){
			map.put("code", 1);
			map.put("errinfo", errinfo);
			return map;
		}
        //新增
		if(bAdd){
	        ordService.add(ord, detailList);
	        session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(1,ord));
		}else{
			ordService.updateOrder(ord, detailList);
	        session.setAttribute(AppointStateEnum.LOG.getStateInfo(),LogJournal.setLogParam(2,ord));
		}
		ord = ordService.findById(orderNo);
		detailList = ordService.findByOrderNo(orderNo);
		map.put("ord", ord);
		map.put("detailList", detailList);
		map.put("code", 0);
		map.put("errinfo", errinfo);
        return map;
    }
    //删除行
    @RequestMapping(value = "/delRow")
    @ResponseBody
    public Map delRow(HttpServletRequest request,HttpServletResponse response, String orderNo,String ids){
    	String rows[] = ids.split(",");
    	for (String rowId : rows) {
    		ordService.delRow(Integer.parseInt(rowId));
		}
    	Map map = new HashMap();
    	List<OrderDetailVo> detailList = ordService.findByOrderNo(orderNo);
		map.put("detailList", detailList);
        return map;
    }
    @RequestMapping(value = "/json")
    @ResponseBody
    public Map json(OrdersVo ord) throws IOException {
        OrdersVo ordList = ordService.findById(ord.getOrderNo());
        Map map=new HashMap();
        map.put("ordList",ordList);
        return map;
    }
    
    @RequestMapping(value = "/materialList")
    @ResponseBody
	//模糊查询物料
	public Map autoCompleteMaterial(String materialCode) throws Exception{
    	Map map=new HashMap();
		if(materialCode !=null && !materialCode.equals(""))
		{
			List<MaterialVo> dataList = ordService.findMaterialByCode(materialCode);
			map.put("dataList",dataList);
		}
		return map;
	}
    @RequestMapping(value = "/materialCheckList")
    @ResponseBody
    //通过订单号从物料检查表查询
	public Map findMaterialCheckByOrderId(OrderDetailVo detail) throws Exception{
    	Map map=new HashMap();
		if(detail.getOrderId() !=null && !detail.getOrderId().equals(""))
		{
			List<OrderDetailVo> dataList = ordService.findDetailByBatchNo(detail);
			map.put("dataList",dataList);
		}
		return map;
	}

    @RequestMapping(value = "/del")
    public String del(HttpServletRequest request,HttpServletResponse response, String ids, PageObject pager, ModelMap map){
    	
    	String id[] = ids.split(",");
    	errinfo="";
    	for (String ordNo : id) {
			OrdersVo order = ordService.findById(ordNo);
			if(order.getAduitStatus()==0){
				ordService.del(ordNo);
			}else{
				errinfo+=ordNo+"单据已审核，不允许删除;";
			}
		}
    	OrdersVo ord = (OrdersVo)request.getSession().getAttribute("ord");
    	map.addAttribute("errinfo", errinfo);
    	return list(request,response,ord,pager,map);
    }
    //新增页面删除单据
    @RequestMapping(value = "/del2")
    public String del2(OrdersVo ord,ModelMap map){
		ordService.del(ord.getOrderNo());
		ord.setOrderType(1);
    	return init(ord,map);
    }

    @RequestMapping(value = "/status")
    public String status(HttpServletRequest request,HttpServletResponse response, String ids, PageObject pager, ModelMap map){
    	errinfo="";
    	String id[] = ids.split(",");
    	for (String ordNo : id) {
    		
    		OrdersVo order = ordService.findById(ordNo);
			if(order.getAduitStatus()==0){
				OrdersVo ord = new OrdersVo();
	    		ord.setInvalid(0);
	    		ord.setOrderNo(ordNo);
				ordService.updateStatus(ord);
			}else{
				errinfo+=ordNo+"单据已审核，不允许作废;";
			}
		}
    	OrdersVo ord = (OrdersVo)request.getSession().getAttribute("ord");
    	map.addAttribute("errinfo", errinfo);
    	return list(request,response,ord,pager,map);
    }
    //新增页面审核
    @RequestMapping(value = "/status2")
    @ResponseBody
    public Map status2(HttpServletRequest request,HttpServletResponse response, String orderNo){
		OrdersVo ord = new OrdersVo();
		ord.setInvalid(0);
		ord.setOrderNo(orderNo);
		ordService.updateStatus(ord);
		Map map = new HashMap();
		map.put("code", 0);
		return map;
    }
    //列表页面审核
    @RequestMapping(value = "/aduit")
    public String aduit(HttpServletRequest request,HttpServletResponse response, String ids, PageObject pager, ModelMap map){
    	errinfo="";
    	String id[] = ids.split(",");
		EmpVo empVo = (EmpVo) session.getAttribute(AppointStateEnum.EMPS.getStateInfo());
    	for (String ordNo : id) {
    		OrdersVo order = ordService.findById(ordNo);
			if(order.getInvalid()==1){
				OrdersVo ord = new OrdersVo();
	    		ord.setAduitDate(ContextUtils.dateToStrLong(new Date()));
	    		ord.setAduitPerson(empVo.getEmpName());
	    		ord.setAduitStatus(1);
	    		ord.setOrderNo(ordNo);
				ordService.updateAduit(ord);
			}else{
				errinfo+=ordNo+"单据已作废，不允许审核;";
			}
			map.addAttribute("errinfo", errinfo);
    		
		}
    	OrdersVo ord = (OrdersVo)request.getSession().getAttribute("ord");
    	map.addAttribute("errinfo", errinfo);
    	return list(request,response,ord,pager,map);
    }
    
    @RequestMapping(value = "/storageList")
    @ResponseBody
    public Map storageList(HttpServletRequest request,HttpServletResponse response, String orderNo){
    	List<StorageVo> storageList = ordService.findAllStorage();
    	Map map = new HashMap();
		map.put("storageList", storageList);
		return map;
    }
    //新增页面审核
    @RequestMapping(value = "/aduit2")
    @ResponseBody
    public Map aduit2(HttpServletRequest request,HttpServletResponse response, String orderNo){
		EmpVo empVo = (EmpVo) session.getAttribute(AppointStateEnum.EMPS.getStateInfo());
		OrdersVo ord = new OrdersVo();
		ord.setAduitDate(ContextUtils.dateToStrLong(new Date()));
		ord.setAduitPerson(empVo.getEmpName());
		ord.setAduitStatus(1);
		ord.setOrderNo(orderNo);
		ordService.updateAduit(ord);
		Map map = new HashMap();
		map.put("code", 0);
		return map;
    }
    @RequestMapping(value = "/update")
    public String update(HttpServletRequest request,HttpServletResponse response, OrdersVo order, PageObject pager, ModelMap map){
    	order = ordService.findById(order.getOrderNo());
    	String sdate = order.getOrderDate();
    	sdate = sdate.substring(0, sdate.indexOf(" "));
    	order.setOrderDate(sdate);
    	map.addAttribute("ord", order);
    	//所有仓库
//        List<StorageVo> storageList = ordService.findAllStorage();
//        map.addAttribute("storageList",storageList);
        //所有供应商
        List<SupplierVo> supplierList = ordService.findAllSupplier();
        map.addAttribute("supplierList",supplierList);
    	return "orderBackAdd";
    }
    @RequestMapping(value = "/getDetail")
    @ResponseBody
    public Map getDetail(String orderNo){
    	Map map = new HashMap();
		List<OrderDetailVo> detailList = ordService.findByOrderNo(orderNo);
		map.put("detailList", detailList);
        return map;

    }
//    审核库存
    @RequestMapping(value = "/getStorageCnt")
    @ResponseBody
    public Map getStorageCnt(OrderDetailVo detail){
    	Map map = new HashMap();
		float cnt = ordService.getStorageCnt(detail);
		map.put("cnt", cnt);
        return map;

    }
}
